﻿using lingopen.Foxconn.RFID.Com;
using lingopen.Foxconn.RFID.Models;
using lingopen.Foxconn.RFID.Sdk;
using System;
using System.IO;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace lingopen.Foxconn.RFID.Reader
{
    public partial class FrmDemo : Form
    {
        public FrmDemo()
        {
            InitializeComponent();
        }
        Com.RichTextBoxLog _log = null; 
        private void FrmView_Load(object sender, EventArgs e)
        {
            _log = new Com.RichTextBoxLog(rtxt);
            //_port = new SerialPortHelper(rtxt);
            //_port.DataReceived += _port_DataReceived;
            string[] serialnums = SerialPortHelper.SerialPortNames;
            toolComPort.Items.AddRange(serialnums);
            btnStart.Enabled = true;
            btnStop.Enabled = false;
        }

        private void _port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;





            //string indata = sp.ReadExisting();
            //_log.LogMessage(indata);


            byte[] buf = new byte[sp.ReadBufferSize];
            int len = 0;
            ////将数据读入内存流
            MemoryStream ms = new MemoryStream();
            len = sp.Read(buf, 0, buf.Length);
            ms.Write(buf, 0, len);
            buf = ms.ToArray();

            string readstr = "";
            foreach (var b in buf)
            {
                if (!readstr.IsNull()) readstr += " ";
                readstr += b.ToString("X2");
            }
            _log.LogMessage(readstr);
        }

        static string epc = "";
        public void HandleData(int hDev, int cmdID, IntPtr pData, int length, IntPtr pHost)
        {
            try
            {
                epc = "";
                byte[] destination = new byte[32];
                byte[] numArray = new byte[32];
                if (length < 5 || length > 30)
                    return;
                Marshal.Copy(pData, destination, 0, length);
                Marshal.Copy(pHost, numArray, 0, 16);
                for (int index = 0; index < length - 4; ++index)
                    epc += string.Format("{0:X2} ", (object)destination[index]);
                epc = epc.Replace(" ", "");
                if (rad16.Checked && epc.Length!=16)
                {
                    _log.LogWarning($"未读取到16位标签");
                    return;
                }
                if (rad24.Checked && epc.Length != 24)
                {
                    _log.LogWarning($"未读取到24位标签");
                    return;
                }

                string str1 = destination[length - 3].ToString();
                string str2 = destination[length - 2].ToString();
                long count = (long)(Convert.ToInt32(str1, 10) * 256 + Convert.ToInt32(str2, 10));

                var tag_epc = new EPC()
                {
                    epc = epc,
                    antNo = (byte)((uint)destination[length - 1] + 1U),
                    devNo = Encoding.Default.GetString(numArray),
                    count = count
                };
                _log.LogMessage($"ANT={tag_epc.antNo},EPC:{tag_epc.epc}");
            }
            catch (Exception ex)
            {
                _log.LogError(ex.Message);
            }
        }

        private int[] hDev = new int[50];
        private NR2k.HANDLE_FUN fun;
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (toolComPort.Text.IsNull())
            {
                _log.LogWarning("请选择COM端口号!");
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                return;
            }


            try
            {
                int index = 0;
                string text = toolComPort.Text;
                byte[] numArray = new byte[32];
                byte[] bytes = Encoding.ASCII.GetBytes(text);
                while (index < 50 && this.hDev[index] != 0)
                    ++index;
                if (index == 50)
                {
                    //int num2 = (int)MessageBox.Show(MainWindow.rm.GetString("MsgChoosebtnConnectOut"));
                    _log.LogError("连接失败!");
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;
                    return;
                }
                else if (NR2k.ConnectDev(ref this.hDev[index], bytes) == 0)
                {
                    byte[] pVer = new byte[32];
                    NR2k.GetDevVersion(this.hDev[index], pVer);
                }
                else
                {
                    _log.LogError("连接失败!");
                    btnStart.Enabled = true;
                    btnStop.Enabled = false;
                    return;
                }

                bool flag = false;
                fun += HandleData;
                for (int i = 0; i < 50; ++i)
                {
                    if (this.hDev[i] != 0)
                    {
                        NR2k.BeginInv(this.hDev[i], fun);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    _log.LogError("设备尚未连接!");
                }
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = true;
                _log.LogMessage("已启动");



            }
            catch (Exception ex)
            {
                _log.LogError($"启动异常:{ex.Message}");
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            //_port.Close();
            //_log.LogWarning("Reader已停止");

            //停止
            bool flag = false;
            try
            {
                for (int index = 0; index < 50; ++index)
                {
                    if (this.hDev[index] != 0)
                    {
                        NR2k.StopInv(this.hDev[index]);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    _log.LogError("设备尚未连接!");

                }

                //断开设备
                for (int index = 0; index < 50; ++index)
                {
                    if (this.hDev[index] != 0)
                    {
                        NR2k.DisconnectDev(ref this.hDev[index]);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    _log.LogError($"断开COM失败!");
                }
                fun -= HandleData;
                this.btnStart.Enabled = true;
                this.btnStop.Enabled = false;
                _log.LogWarning("已停止");
            }
            catch (Exception ex)
            {
                _log.LogError($"停止异常:{ex.Message}");
            }
        }
    }
}
